package com.loginCheck.filter;

import com.loginCheck.pojo.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

// @WebFilter("/*")
public class LoginCheckFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("初始化...");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //设置编码
        servletRequest.setCharacterEncoding("utf-8");

        //向下转型
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        //获取请求的uri路径
        String uri = request.getRequestURI();

        //对uri进行判断，是否包含/LoginCheckServlet，如果有就放行
        if (uri.endsWith("/loginCheckServlet") || uri.endsWith("/login.jsp")
                || uri.endsWith("/success.jsp") || uri.endsWith("/index.jsp")) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            //获取session对象
            HttpSession session = request.getSession();

            //获取域中的对象
            User user = (User) session.getAttribute("user");

            //判断user对象是否为null
            if (user == null) {//未登录不放行
                //向域中存储message数据
                request.setAttribute("message", "您未登录，请先登录~");
                request.getRequestDispatcher("/jsp/login.jsp").forward(servletRequest, servletResponse);
            } else {//已登录放行
                filterChain.doFilter(servletRequest, servletResponse);
            }
        }
    }

    @Override
    public void destroy() {
        System.out.println("LoginCheckFilter被销毁...");
    }
}
